package com.ruleengine.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruleengine.util.exception.JsonException;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lianghanwei on 2024/3/20
 */
@Slf4j
public class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static JsonNode parseJsonNode(String json) {
        try {
            return objectMapper.readTree(json);
        } catch (IOException e) {
            log.error("Parse jsonNode failed", e);
            throw new JsonException("Parse jsonNode failed", e);
        }
    }

    public static String toPrettyJson(JsonNode jsonNode) {
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        } catch (JsonProcessingException e) {
            throw new JsonException("To pretty json failed", e);
        }
    }
}
